$(document).ready(function() {
    var lastPostId; 
    var href = '/post';
    var path = location.pathname;
    var department = path.match(/\/department\/([^/]*)/);
    if (department) {               
        href = '/department/' + department[1] + '/post';
    }
    var renderData = function(data) {
        for (var i in data) {
            var post = data[i];
            
            var title = post.title?post.title:'';            
            var media = post.preview_mediadata?post.preview_mediadata:'';
            var text  = post.preview_text?post.preview_text:'';

            var html  = '<article class="blog-post span8" id="'+post.id+'">';
                html +=   '<div class="block-dark">';
                html +=     '<div class="block-light">';
                html +=       '<div class="wrapper-img">';
                html +=         '<a><center>'+media+'</center></a>';
                html +=       '</div>';
                html +=       '<div class="wrapper">';
                html +=         '<h2 class="post-title">';
                html +=           '<a href="#">'+title+'</a>';
                html +=         '</h2>';
                html +=         '<b>' + post.date_create + '</b>'; 
                html +=         '<p>';
                html +=           text;
                html +=           '<a href="'+href+'/'+post.alias+'" class="read-more">[Подробнее]</a>';
                html +=         '</p>';
                html +=         '<p class="tags">Теги:';
                for (var j in post.tags) {
                    var tag = post.tags[j];                 
                    html += '<a href="/posts-by-tag/tag_id/'+tag.id+'">';
                    html += tag.tag_name;
                    html += '</a>';
                }
                html +=         '</p>';
                html +=       '</div>';
                html +=     '</div>';
                html +=   '</div>';
                html += '</article>';
                $('#feed').append(html);
        }       
    }

    var loadFeed = function(lastPostId) {       
        $.post('/ajax/load-feed', {post_id: lastPostId}, function(r) {
            var resp = JSON.parse(r);            
            renderData(resp.result);
            bindAppearToLastPost();
        })
    }

    var bindAppearToLastPost = function() {
        $('.blog-post:last').appear();
        $('.blog-post:last').on('appear', function() {
            if (lastPostId != $(this).attr('id')) {
                lastPostId = $(this).attr('id');
                loadFeed(lastPostId);
                $('.blog-post:last').appear();
            }            
        });
    }   
    bindAppearToLastPost();
})